package com.hui.auth.exception;

import com.hui.auth.dto.JsonResult;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 权限模块异常处理
 * Created by LiaoYunHui on 2017/10/26/026.
 */
@ControllerAdvice
public class AuthExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(AuthExceptionHandler.class);

    /**
     * Redis连接错误
     */
    @ResponseBody
    @ExceptionHandler(RedisConnectionFailureException.class)
    public JsonResult<String> exceptionHandler(RedisConnectionFailureException e) {
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setMsg(AuthError.REDIS_CONNECTION_FAILURE.msg);
        jsonResult.setCode(AuthError.REDIS_CONNECTION_FAILURE.code);
        logger.debug("exceptionHandler {}", e);
        return jsonResult;
    }

    /**
     * 未知用户名
     */
    @ResponseBody
    @ExceptionHandler(UnknownAccountException.class)
    public JsonResult<String> exceptionHandler(UnknownAccountException e) {
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setCode(AuthError.TOKEN_AUTH_ERROR.code);
        jsonResult.setMsg(AuthError.TOKEN_AUTH_ERROR.msg);
        logger.debug("exceptionHandler {}", e);
        return jsonResult;
    }

    /**
     * 账号锁定
     */
    @ResponseBody
    @ExceptionHandler(LockedAccountException.class)
    public JsonResult<String> exceptionHandler(LockedAccountException e) {
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setCode(AuthError.TOKEN_AUTH_LOCKED.code);
        jsonResult.setMsg(AuthError.TOKEN_AUTH_LOCKED.msg);
        logger.debug("exceptionHandler {}", e);
        return jsonResult;
    }

    /**
     * 密码错误
     */
    @ResponseBody
    @ExceptionHandler(IncorrectCredentialsException.class)
    public JsonResult<String> exceptionHandler(IncorrectCredentialsException e) {
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setCode(AuthError.TOKEN_AUTH_ERROR.code);
        jsonResult.setMsg(AuthError.TOKEN_AUTH_ERROR.msg);
        logger.debug("exceptionHandler {}", e);
        return jsonResult;
    }
}
